package ay.shadow.nacos.config;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.spring.util.PropertySourcesUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class NacosDiscoveryPropertiesV2 extends NacosDiscoveryProperties {

    @Autowired
    private Environment environment;

    public void enrichNacosDiscoveryProperties(Properties nacosDiscoveryProperties) {
        Map<String, Object> properties = PropertySourcesUtils
                .getSubProperties((ConfigurableEnvironment) environment, PREFIX);
        properties.forEach((k, v) -> nacosDiscoveryProperties.putIfAbsent(resolveKey(k),
                String.valueOf(v)));
    }
    private static final Pattern PATTERN = Pattern.compile("-(\\w)");
    private String resolveKey(String key) {
        Matcher matcher = PATTERN.matcher(key);
        StringBuilder sb = new StringBuilder();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
}
